package hhm.android.main

import android.os.Bundle
import android.text.TextUtils
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.datePicker.bean.DateParams
import hhm.android.library.utils.DialogUtils
import hhm.android.library.utils.GetDateListener
import hhm.android.library.utils.GetStringListener
import hhm.android.library.weightHeightPicker.heightPicker.HeightParams
import hhm.android.main.databinding.ActivityInputHeightByHandBinding
import siau.android.base.HttpHelper
import siau.android.base.SBApplication
import siau.android.base.SBBaseActivity
import siau.android.base.analyseDataBeforeSet
import siau.android.base.enum.HeightClass
import siau.android.http.model.RecordHeightDataRequest
import siau.android.http.model.RecordWeightDataRequest
import siau.android.library.KeyString
import java.text.SimpleDateFormat
import java.util.*

class InputHeightByHandActivity : SBBaseActivity() {

    lateinit var dataBinding: ActivityInputHeightByHandBinding
    private var childId: Int = -1
    private var data = ""
    private var timeChange = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_input_height_by_hand)
        initTitleWithLine(getString(R.string.input_by_hand))
        dataBinding.lifecycleOwner = this

        childId = intent.getIntExtra(KeyString.childId, -1)
        var oldData = intent.getDoubleExtra(KeyString.data, 0.0)

        val dateParams = HeightParams()
        dateParams.types = IntArray(2)
        when (SBApplication.userData.heightUnit) {
            HeightClass.CM.msg -> {
                dateParams.types[0] = HeightParams.TYPE_CM
                dateParams.types[1] = HeightParams.TYPE_MM
                if (oldData.isNaN() || oldData == 0.0) {
                    oldData = 20.0
                    dataBinding.activityInputHeightByHandTv.text = "20.0cm"
                    data = "20.0"
                } else {
                    dataBinding.activityInputHeightByHandTv.text = "${oldData}cm"
                    data = oldData.toString()
                }
            }
            HeightClass.FT.msg -> {
                dateParams.types[0] = HeightParams.TYPE_FT
                dateParams.types[1] = HeightParams.TYPE_IN
                if (oldData.isNaN() || oldData == 0.0) {
                    oldData = 0.8
                    dataBinding.activityInputHeightByHandTv.text = "0ft8in"
                    data = "0.8"
                } else {
                    dataBinding.activityInputHeightByHandTv.text = analyseDataBeforeSet(oldData.toString(), 2, HeightClass.FT.msg)
                    data = oldData.toString()
                }
            }
        }

        dataBinding.wheelLayout.show(SBApplication.userData.heightUnit, oldData, dateParams, ContextCompat.getColor(this, R.color.mainTextColor))
        dataBinding.wheelLayout.setOnChangeListener(object : GetStringListener {
            override fun getString(s: String) {
                if (SBApplication.userData.heightUnit == HeightClass.CM.msg) {
                    dataBinding.activityInputHeightByHandTv.text = s + getString(R.string.class_cm)
                } else {
                    dataBinding.activityInputHeightByHandTv.text = analyseDataBeforeSet(s, 2, HeightClass.FT.msg)
                }
                data = s
            }
        })

        val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm")
        val time = sdf.format(Date())
        val times = time.split(" ")
        dataBinding.activityInputHeightByHandDate.text = times[0]
        dataBinding.activityInputHeightByHandTime.text = times[1]

        dataBinding.activityInputHeightByHandSelectDate.setOnClickListener {
            DialogUtils.showDatePicBottomView(
                this,
                object : GetDateListener {
                    override fun getDate(date: Date, string: String) {
                        dataBinding.activityInputHeightByHandDate.text = string
                    }
                },
                "yyyy/MM/dd",
                DateParams.TYPE_YEAR, DateParams.TYPE_MONTH, DateParams.TYPE_DAY,
            )
        }
        dataBinding.activityInputHeightByHandSelectTime.setOnClickListener {
            DialogUtils.showDatePicBottomView(
                this, object : GetDateListener {
                    override fun getDate(date: Date, string: String) {
                        timeChange = true
                        dataBinding.activityInputHeightByHandTime.text = string
                    }
                }, "HH:mm", DateParams.TYPE_HOUR, DateParams.TYPE_MINUTE
            )
        }
        dataBinding.activityInputHeightByHandBtn.setOnClickListener {
            showLoadingFragment(R.id.activity_input_height_by_hand_fl)
            val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
            val time = sdf.format(Date())
            val times = time.split(" ")
            val ss = times[1].split(":")
            var d = if (timeChange) {
                sdf.parse(dataBinding.activityInputHeightByHandDate.text.toString() + " " + dataBinding.activityInputHeightByHandTime.text.toString() + ":" + ss[2])
            } else {
                sdf.parse(dataBinding.activityInputHeightByHandDate.text.toString() + " " + times[1])
            }
            val r: RecordHeightDataRequest
            if (SBApplication.userData.heightUnit == HeightClass.CM.msg) {
                r = RecordHeightDataRequest(childId, d.time, 2, data, heightUnit = SBApplication.userData.heightUnit)
            } else {
                val double: Double = if (data.contains(".")) {
                    val split = data.split(".")
                    if (split[0].toInt() == 0) {
                        split[1].toInt() * 2.54
                    } else {
                        if (split[1].toInt() == 0) {
                            split[0].toInt() * 30.48
                        } else {
                            split[0].toInt() * 30.48 + split[1].toInt() * 2.54
                        }
                    }
                } else {
                    data.toInt() * 30.48
                }
                r = RecordHeightDataRequest(childId, d.time, 2, double.toString(), heightUnit = HeightClass.CM.msg)
            }

            HttpHelper().recordHeight(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                removeLoadingFragment()
                setResult(1001)
                finish()
            }, {
                removeLoadingFragment()
                showToast(it.message)
            })
        }
    }
}